import 'package:ball_lion/module/loading/loading_expert_list.dart';
import 'package:easy_refresh/easy_refresh.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:extended_tabs/extended_tabs.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/expert/expert_page_logic.dart';
import 'package:ball_lion/entity/expert/plan_filter_entity.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/resources/styles.dart';
import 'package:ball_lion/routes/routes.dart';
import 'package:ball_lion/utils/user.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/module/expert/items/hot_expert_item.dart';
import 'package:ball_lion/widgets/base/wqs_carousel_view.dart';
import 'package:ball_lion/module/home/news_button_area.dart';
import 'package:ball_lion/server/api/user_api.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';
import 'package:ball_lion/widgets/ads_label.dart';
import 'package:ball_lion/widgets/card.dart';
import 'package:ball_lion/widgets/loading/loading_widget.dart';
import 'package:ball_lion/widgets/loading/no_data_widget.dart';
import 'items/plan_list_item.dart';
import 'items/suggest_expert_widget.dart';

class ExpertPage extends StatefulWidget {
  const ExpertPage({super.key, required this.sportsId});

  final int sportsId;

  @override
  State<ExpertPage> createState() => _ExpertPageState();
}

class _ExpertPageState extends State<ExpertPage>
    with AutomaticKeepAliveClientMixin {
  late ExpertPageLogic logic =
      Get.put(ExpertPageLogic(), tag: "${widget.sportsId}");

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return GetBuilder<ExpertPageLogic>(
        tag: "${widget.sportsId}",
        initState: (state) {
          logic.checkSports(widget.sportsId);
          if (User.isLogin) {
            UserApi.myFocusUser(1, 100).then((value) {
              if ((value?.length ?? 99) < 30 &&
                  SpUtils.suggestExpert <
                      DateTime.now().microsecondsSinceEpoch) {
                Get.bottomSheet(
                    SuggestExpertWidget.sheet(sportsId: widget.sportsId));
                SpUtils.suggestExpert = DateTime.now()
                    .add(const Duration(days: 7))
                    .microsecondsSinceEpoch;
              }
            });
          }
        },
        builder: (logic) {
          return Stack(
            children: [
              EasyRefresh.builder(
                controller: logic.refreshC,
                scrollController: logic.refreshScroll,
                header: Styles.refreshHeader(
                    position: IndicatorPosition.locator,
                    clamping: true,
                    backgroundColor: Colours.transparent),
                footer:
                    Styles.refreshFooter(position: IndicatorPosition.locator),
                onRefresh: logic.getRefresh,
                onLoad: logic.loadMore,
                childBuilder: (BuildContext context, ScrollPhysics physics) =>
                    ScrollConfiguration(
                  behavior: const ERScrollBehavior(),
                  child: ExtendedNestedScrollView(
                      controller: logic.refreshScroll,
                      physics: physics,
                      pinnedHeaderSliverHeightBuilder: () => 40,
                      headerSliverBuilder: (context, innerBoxIsScrolled) => [
                            const HeaderLocator.sliver(clearExtent: false),
                            if (logic.lbt.hasValue)
                              SliverToBoxAdapter(
                                child: GetBuilder<ExpertPageLogic>(
                                    id: "carousel",
                                    tag: "${widget.sportsId}",
                                    builder: (logic) {
                                      return Container(
                                        width: Get.width,
                                        decoration: const BoxDecoration(
                                            gradient: LinearGradient(
                                          colors: [
                                            Colours.white,
                                            Colours.greyF2F3F7
                                          ],
                                          begin: Alignment.topCenter,
                                          end: Alignment.bottomCenter,
                                          // stops: [0.2,0.3]
                                        )),
                                        child: QsCarouselView(
                                          key: Key("${DateTime.now()}"),
                                          aspectRatio: 359 / 120,
                                          radius: 8,
                                          padding: 8,
                                          needDot: (logic.lbt ?? []).length > 1,
                                          carousels: logic.lbt ?? [],
                                          tapType: "caijin_banner",
                                          needTitle: false,
                                          autoPlay: logic.carouselPlay,
                                        ).paddingOnly(top: 8),
                                      );
                                    }),
                              ),
                            SliverToBoxAdapter(
                                child: Container(
                                    color: Colours.greyF2F3F7,
                                    height: 8,
                                    width: Get.width)),
                            if (logic.menus.hasValue)
                              SliverToBoxAdapter(
                                child: Container(
                                  color: Colours.greyF2F3F7,
                                  child: Block(
                                      cardStyle: const CardStyle(
                                          margin:
                                              EdgeInsets.fromLTRB(8, 0, 8, 0)),
                                      child: NewsButtonArea(
                                          menus: logic.menus,
                                          tapType: "caijin_portal")),
                                ),
                              ),
                            if (logic.couponPack != null)
                              // SliverToBoxAdapter(
                              //   child: CouponSaleItem(
                              //     entity: logic.couponPack,
                              //     margin: const EdgeInsets.fromLTRB(8, 8, 8, 0),
                              //   ),
                              // ),
                              if (logic
                                  .hotExpert[logic.sportsId - 1].hasValue) ...[
                                SliverToBoxAdapter(
                                    child: Container(
                                        color: Colours.greyF2F3F7,
                                        height: 8,
                                        width: Get.width)),
                                SliverToBoxAdapter(child: hotBoard())
                              ],
                            SliverToBoxAdapter(child: tabBar())
                          ],
                      body: ExtendedTabBarView(
                          controller: logic.tabController,
                          children: List.generate(logic.tabs.length, (index) {
                            var tip = "";
                            switch (index) {
                              case 0:
                                tip = "关注专家暂无方案";
                                break;
                              case 3:
                                tip = "暂无免费方案";
                                break;
                              default:
                                tip = "暂无相关方案";
                            }
                            return Container(
                              color: Colours.greyF2F3F7,
                              child:
                                  CustomScrollView(physics: physics, slivers: [
                                SliverToBoxAdapter(child: Container(height: 4)),
                                LoadingWidget<bool>.sliver(
                                  isLoading: false,
                                  data: !User.isLogin && index == 0,
                                  noData: NoDataWidget.sliver(
                                      physics: physics,
                                      tip: "请登录后查看",
                                      buttonText: "去登录",
                                      onTap: () => User.needLogin(
                                          () async => logic.getRefresh())),
                                  child: () => LoadingWidget<bool>.sliver(
                                    isLoading: logic.pages[index] == null,
                                    data: logic.pages[index]?.length == 0,
                                    loading: SliverToBoxAdapter(
                                        child: const LoadingExpertWidget()
                                            .loadingExpertList(false)),
                                    noData: index == 0
                                        ? SliverLayoutBuilder(
                                            builder: (context, cons) =>
                                                SliverToBoxAdapter(
                                                    child: SuggestExpertWidget
                                                        .grid(
                                                            sportsId:
                                                                widget.sportsId,
                                                            tapFocus: logic
                                                                .getRefresh,
                                                            noData: SizedBox(
                                                              height: cons
                                                                  .viewportMainAxisExtent,
                                                              child:
                                                                  NoDataWidget(
                                                                physics:
                                                                    physics,
                                                                tip: tip,
                                                              ),
                                                            ))),
                                          )
                                        : NoDataWidget.sliver(
                                            physics: physics,
                                            tip: tip,
                                          ),
                                    child: () => SliverList.builder(
                                        itemCount:
                                            (logic.pages[index]?.length ?? 0) >
                                                    5
                                                ? logic.pages[index]!.length + 1
                                                : logic.pages[index]!.length,
                                        itemBuilder:
                                            (BuildContext context, int i) {
                                          if (i == 4) {
                                            return AdsLabel(
                                                adsTag: 'expert_$index',
                                                tapType: 'caijin_advertising');
                                          } else {
                                            return Block(
                                              cardStyle: const CardStyle(
                                                  margin: EdgeInsets.fromLTRB(
                                                      8, 0, 8, 8),
                                                  padding: EdgeInsets.symmetric(
                                                      horizontal: 12)),
                                              child: PlanListItem(
                                                tabId: logic.tabId[index],
                                                planList: logic.pages[index]![
                                                    i > 4 ? i - 1 : i],
                                                eventType: "caijin_plan_view",
                                              ),
                                            );
                                          }
                                        }),
                                  ),
                                ),
                                if (logic.pages[index].hasValue)
                                  const FooterLocator.sliver(),
                                SliverToBoxAdapter(
                                  child: Container(height: 50),
                                )
                              ]),
                            );
                          }))),
                ),
              ),
              if (logic.showMenu)
                Positioned.fill(
                  top: 40,
                  child: GestureDetector(
                      onTap: () {
                        logic.showMenu = false;
                        logic.menuController.reverse();
                      },
                      onVerticalDragStart: (drag) {
                        logic.showMenu = false;
                        logic.menuController.reverse();
                      },
                      child: Container(
                        color: Colours.black.withOpacity(0.5),
                      )),
                ),
              Padding(
                padding: const EdgeInsets.only(top: 40),
                child: Transform.scale(
                  scaleY: logic.menuAnimation.value,
                  alignment: Alignment.topCenter,
                  child: Container(
                      clipBehavior: Clip.none,
                      decoration: const BoxDecoration(
                          color: Colours.white,
                          border: Border(
                              top: BorderSide(
                                  color: Colours.greyEE, width: 0.5))),
                      child: menu()),
                ),
              ),
            ],
          );
        });
  }

  Widget tabBar() {
    return Container(
        height: 40,
        padding: const EdgeInsets.symmetric(horizontal: 8),
        decoration: BoxDecoration(
            border: Border(
                bottom: BorderSide(
                    color: logic.toTop ? Colours.greyEE : Colours.transparent,
                    width: 0.5))),
        child: Styles.tabbar(
            tabs: List.generate(
                logic.tabs.length,
                (index) => Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        QsText(logic.tabs[index]),
                        // if (index == 1 && logic.sportsId == 1)
                        //   Icon(
                        //       logic.showMenu
                        //           ? GetIcon.menu_arrow_up
                        //           : GetIcon.menu_arrow_down,
                        //       size: 12)
                      ],
                    )),
            controller: logic.tabController,
            // scrollable: true,
            fontSize: 16,
            labelPadding: const EdgeInsets.symmetric(horizontal: 0),
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            onTap: (value) async {
              Utils.onEvent('caijin_plan_tab',
                  params: {'tab': logic.tabs[value]});
              // if (value == 1 && !logic.tabController.indexIsChanging) {
              //   logic.refreshScroll
              //       .jumpTo(logic.refreshScroll.position.maxScrollExtent);
              //   logic.showMenu = !logic.showMenu;
              //   if (logic.showMenu) {
              //     logic.menuController.forward();
              //   } else {
              //     logic.menuController.reverse();
              //   }
              // }
              logic.tabIndex = value;
            }));
  }

  Widget hotScrollBar() {
    return Container(
      height: 24,
      decoration: const BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(33.5)),
          color: Colours.white),
      child: ExtendedTabBar(
          physics: const ClampingScrollPhysics(),
          tabs: List.generate(
              logic.hotFilter.length,
              (index) => Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  child: QsText(logic.hotFilter[index]))),
          controller: logic.hotController,
          indicator: BoxDecoration(
              borderRadius: BorderRadius.circular(33.5),
              color: const Color(0xFFFCECEA),
              border: Border.all(color: Colours.main, width: 0.5)),
          isScrollable: true,
          indicatorWeight: 0,
          indicatorSize: TabBarIndicatorSize.label,
          labelColor: Colours.main,
          labelPadding: EdgeInsets.zero,
          unselectedLabelColor: Colours.grey66,
          labelStyle: const TextStyle(fontSize: 12),
          unselectedLabelStyle: const TextStyle(fontSize: 12),
          onTap: (value) => logic.setHotTabIndex(value)),
    );
  }

  Widget hotBoard() {
    return Container(
      color: Colours.greyF2F3F7,
      child: Block(
          cardStyle: const CardStyle(
            margin: EdgeInsets.fromLTRB(8, 0, 8, 0),
          ),
          child: Stack(
            alignment: Alignment.topCenter,
            children: [
              Image.asset(Utils.getImgPath("expert_hot_bg.png")),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Container(height: 10),
                  Row(
                    children: [
                      hotScrollBar(),
                      const Spacer(),
                      GestureDetector(
                          behavior: HitTestBehavior.translucent,
                          onTap: () {
                            Utils.onEvent('caijin_hot_expert_rank');
                            Get.toNamed(Routes.expertTop,
                                arguments: logic.sportsId - 1);
                          },
                          child: Row(
                            children: [
                              const QsText("专家榜",
                                  fontSize: 12, color: Colours.grey99),
                              Image.asset(
                                  Utils.getImgPath("arrow_right_36.png"),
                                  width: 12)
                            ],
                          ))
                    ],
                  ).paddingSymmetric(horizontal: 8),
                  MediaQuery.removePadding(
                    context: context,
                    removeTop: true,
                    child: GridView.count(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      crossAxisCount: 5,
                      mainAxisSpacing: 12,
                      childAspectRatio: 1 / 1.17,
                      children: List.generate(
                          logic.hotExpert[logic.sportsId - 1]?.length ?? 0,
                          (i) => HotExpertItem(
                              entity: logic.hotExpert[logic.sportsId - 1]?[i],
                              sportsId: logic.sportsId,
                              eventType: 'caijin_hot_expert')),
                    ),
                  ).paddingSymmetric(vertical: 12, horizontal: 4)
                ],
              )
            ],
          )),
    );
  }

  Widget menu() {
    return DefaultTextStyle(
      style: const TextStyle(fontSize: 12, color: Colours.text),
      child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Container(height: 12),
            menuType(0, [Filter(name: "全部方案", cnt: logic.menu?.total)]),
            Container(height: 12),
            if (logic.menu?.kind.hasValue == true) ...[
              const QsText("比赛所属分类", fontWeight: FontWeight.w500),
              Container(height: 12),
              menuType(1, logic.menu?.kind ?? []),
              Container(height: 12),
            ],
            if (logic.menu?.playType.hasValue == true) ...[
              const QsText("玩法分类", fontWeight: FontWeight.w500),
              Container(height: 12),
              menuType(2, logic.menu?.playType ?? []),
              Container(height: 12),
            ],
            if (logic.menu?.league.hasValue == true) ...[
              const QsText("联赛分类", fontWeight: FontWeight.w500),
              Container(height: 12),
              menuType(3, logic.menu?.league ?? []),
              Container(height: 18),
            ]
          ]).paddingSymmetric(horizontal: 16),
    );
  }

  Widget menuType(int i, List<Filter>? entity) {
    return MediaQuery.removePadding(
      context: context,
      removeTop: true,
      child: GridView.count(
          physics: const NeverScrollableScrollPhysics(),
          shrinkWrap: true,
          crossAxisCount: 4,
          crossAxisSpacing: 8,
          mainAxisSpacing: 12,
          childAspectRatio: ((Get.width - 24 - 32) / 4) / 28,
          children: List.generate(
              entity?.length ?? 0,
              (index) => Container(
                    padding: const EdgeInsets.symmetric(horizontal: 6),
                    decoration: BoxDecoration(
                        color: logic.menuIndex.containsKey(i) &&
                                logic.menuIndex.containsValue(index)
                            ? Colours.main.withOpacity(0.1)
                            : Colours.white,
                        borderRadius: BorderRadius.circular(4),
                        border: Border.all(
                            color: logic.menuIndex.containsKey(i) &&
                                    logic.menuIndex.containsValue(index)
                                ? Colours.main.withOpacity(0.4)
                                : Colours.greyCC,
                            width: 0.5,
                            strokeAlign: BorderSide.strokeAlignOutside)),
                    child: Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Flexible(
                              child: QsText(entity?[index].name ?? "",
                                  color: logic.menuIndex.containsKey(i) &&
                                          logic.menuIndex.containsValue(index)
                                      ? Colours.main
                                      : Colours.text,
                                  needCenter: true))
                        ]),
                  ).tap(() {
                    logic.menuIndex = {i: index};
                    logic.menuChoice = {i: entity![index]};
                    logic.showMenu = false;
                    logic.menuController.reverse();
                  }))),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
